package cn.xiehang.SoundSight;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {


    private OkHttpClient client;
    private ProgressDialog progressDialog;
    private CheckBox cbAgree;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);




        // 初始化 ProgressDialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("请稍等片刻...");
        progressDialog.setCancelable(false);


        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        EditText userName = findViewById(R.id.username_input);
        EditText passWord = findViewById(R.id.password_input);
        cbAgree = findViewById(R.id.cbAgree);

        TextView tvTerms = findViewById(R.id.tvTerms);

        // 点击条款文字显示服务条款对话框
        tvTerms.setOnClickListener(v -> showTermsDialog());

        
        Button passWordShowOrHide = findViewById(R.id.password_show_or_hide);

        passWordShowOrHide.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void onClick(View v) {
                // 处理按钮点击事件
                if (passWord.getInputType() == 129) {
                    passWord.setInputType(128);
                    passWordShowOrHide.setBackground(getDrawable(R.drawable.show_password));
                } else {
                    passWord.setInputType(129);
                    passWordShowOrHide.setBackground(getDrawable(R.drawable.hide_password));
                }
            }
        });


        Button forgot = findViewById(R.id.forgot_button);

        //如果忘记密码，就转跳到忘记密码页面
        forgot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理按钮点击事件
                Intent intent = new Intent(MainActivity.this, ForgetPage.class);
                startActivity(intent);
            }
            });

        Button login = findViewById(R.id.login_button);
        login.setEnabled(false);
        // 监听复选框状态改变
        cbAgree.setOnCheckedChangeListener((buttonView, isChecked) -> {
            login.setEnabled(isChecked);
        });


        //如果登录成功，就转跳到主页面
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String username = userName.getText().toString();
                String password = passWord.getText().toString();


                // 发起网络请求
                performLogin(username, password);

            }
            });

        Button register = findViewById(R.id.register_button);

        //如果没有账号，就转跳到注册页面
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理按钮点击事件
                Intent intent = new Intent(MainActivity.this, RegisterPage.class);
                startActivity(intent);


            }
            });

        Button tourist_mode = findViewById(R.id.tourist_mode_button);
        //判断是否有存留的账号
        SharedPreferences sharedPref = getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        boolean isLoggedIn = sharedPref.getBoolean("is_logged_in", false);
        if (isLoggedIn) {
            // 如果有存留的账号，直接跳转到主页面
            tourist_mode.setText("登录上次使用的账号");
        }


        //游客模式
        tourist_mode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理按钮点击事件
                Intent intent = new Intent(MainActivity.this, MainPage.class);
                startActivity(intent);
            }
        });


        }

    private void showTermsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_terms, null);
        builder.setView(dialogView);

        AlertDialog dialog = builder.create();

        // 设置对话框大小
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);

        Button btnAccept = dialogView.findViewById(R.id.btnAccept);
        btnAccept.setOnClickListener(v -> {
            cbAgree.setChecked(true);
            dialog.dismiss();
        });

        dialog.show();
    }

    private void performLogin(String username, String password) {
        // 显示等待弹窗
        progressDialog.show();

        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        String jsonString = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";
        RequestBody body = RequestBody.create(jsonString, JSON);

        Request request = new Request.Builder()
                .url(SeverURL.URL+"/login")
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();



        client = new OkHttpClient();
        // 异步执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败时，关闭弹窗
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    // 显示错误信息或其他操作
                    Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                });
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //如果状态码是400，表示登录失败，将返回信息转化为json格式，并打印message
                if (response.code() == 400) {
                    runOnUiThread(() -> {
                        progressDialog.dismiss();
                        // 显示错误信息或其他操作
                        String json = null;
                        try {
                            json = response.body().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Gson gson = new Gson();
                        HashMap<String, String> map = gson.fromJson(json, HashMap.class);
                        String message = map.get("message");
                        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    });
                }
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    // 处理响应数据
                    if (response.isSuccessful()) {
                        // 登录成功，跳转到主页面
                        SharedPreferences sharedPref = getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPref.edit();
                        editor.putString("username", username);
                        editor.putString("password",password);
                        editor.putBoolean("is_logged_in", true);
                        editor.commit();
                        Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(MainActivity.this, MainPage.class);
                        startActivity(intent);
                        }
                });
            }
        });
    }
    }


